package com.dailyblue.java.servlet.controller;

import com.dailyblue.java.jdbc.pack0325.bean.User;
import com.dailyblue.java.jdbc.pack0325.serivce.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/user_login")
public class UserLoginController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 1. 处理中文乱码
        request.setCharacterEncoding("utf-8");
        // 2. 接收账号密码
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String yzm = request.getParameter("yzm"); // 获取输入的验证码
        // 校验输入的验证码和系统生成的验证码
        Object systemYzm = request.getSession().getAttribute("YZM");
        if(!yzm.equalsIgnoreCase(systemYzm.toString())){
            request.getSession().setAttribute("ERROR", "验证码输入错误！");
            response.sendRedirect("login.jsp");
            return;
        }
        // 3. 产生service对象并调用登陆方法
        UserService service = new UserService();
        User user = service.login(name, password);
        // 4. 根据返回结果来跳转到不同的页面
        if (user == null) {
            // 4.1 说明用户登陆失败
            request.getSession().setAttribute("ERROR", "账号或者密码错误！");
            response.sendRedirect("login.jsp");
            return;
        }
        // 4.2 登陆成功后的操作
        // 保存用户信息
        request.getSession().setAttribute("USER", user);
        response.sendRedirect("main.jsp");
    }
}
